package org.example.erp.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.erp.domain.UserLoginLog;
import org.example.erp.service.impl.UserLoginLogServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.List;

@RestController
@RequestMapping("/api")
public class LoginLogController {
    @Autowired
    private UserLoginLogServiceImpl userLoginLogService;

    /**
     * 删除记录
     *
     * @param logIds 集合
     * @return DataResult 封装对象
     */
    @DeleteMapping("/loginLog/delete")
    public DataResult deleteLoginLog(@RequestBody List<Integer> logIds) {
        if (logIds.isEmpty()) {
            // 执行清空,删除全部
            userLoginLogService.remove(null);
        } else {
            // 执行删除单个或多个
            userLoginLogService.removeByIds(logIds);
        }
        return DataResult.success();
    }

    /**
     * 查询方法
     *
     * @param currentPage 当前页码
     * @param pageSize    展示条数
     * @param ipAddr      ip地址
     * @param username    用户名
     * @param status      状态
     * @param start       开始时间
     * @param over        结束时间
     * @return DataResult结果对象
     */
    @GetMapping("/loginLog/find")
    public DataResult findLoginLog(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                   @RequestParam(value = "pageSize", defaultValue = "1") Integer pageSize,
                                   @RequestParam(required = false) String ipAddr, @RequestParam(required = false) String username, @RequestParam(required = false) String status,
                                   @RequestParam(required = false) String start, @RequestParam(required = false) String over) {
        LambdaQueryWrapper<UserLoginLog> userLoginLog = new LambdaQueryWrapper<>();
        IPage<UserLoginLog> page = new Page<>(currentPage, pageSize);
        //链式调用,前面是表达式，判断条件是否成立
        userLoginLog.like(!"".equals(ipAddr) && ipAddr != null, UserLoginLog::getIpAddr, ipAddr)
                .like(!"".equals(username) && username != null, UserLoginLog::getUserName, username)
                .eq(!"".equals(status) && status != null, UserLoginLog::getStatus, status)
                .between((!"".equals(start) && !"".equals(over)) && (start != null && over != null), UserLoginLog::getLoginTime, start, over);
        IPage<UserLoginLog> pageResult = userLoginLogService.page(page, userLoginLog);
        return DataResult.success(pageResult);
    }

    @PostMapping("/loginLog/insert")
    public DataResult insertLoginLog(@RequestBody UserLoginLog userLoginLog) {
        userLoginLogService.save(userLoginLog);
        return DataResult.success();
    }

    @GetMapping("/loginLog/export")
    public void exportExcel(HttpServletResponse response, @RequestParam(value = "currentPage", required = false) Integer currentPage,
                            @RequestParam(value = "pageSize", required = false) Integer pageSize,
                            @RequestParam(required = false) String ipAddr, @RequestParam(required = false) String username, @RequestParam(required = false) String status,
                            @RequestParam(required = false) String start, @RequestParam(required = false) String over) {
        LambdaQueryWrapper<UserLoginLog> userLoginLog = new LambdaQueryWrapper<>();
//        //链式调用,前面是表达式，判断条件是否成立
        userLoginLog.like(!"".equals(ipAddr) && ipAddr != null, UserLoginLog::getIpAddr, ipAddr)
                .like(!"".equals(username) && username != null, UserLoginLog::getUserName, username)
                .eq(!"".equals(status) && status != null, UserLoginLog::getStatus, status)
                .between((!"".equals(start) && !"".equals(over)) && (start != null && over != null), UserLoginLog::getLoginTime, start, over);
        List<UserLoginLog> list = userLoginLogService.list(userLoginLog);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=loginlog"+Instant.now().toEpochMilli()+".xlsx");
        try{
            ServletOutputStream out = response.getOutputStream();
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet(); //创建工作表
            XSSFRow row = sheet.createRow(0); //创建一行从0开始
            String[] columnName = new String[]{"日志编号", "用户名称", "IP地址", "登录地址", "浏览器类型", "操作系统",
                    "登录状态", "操作信息", "登录时间"};
            for (int i = 0; i < columnName.length; i++) {
                row.createCell(i).setCellValue(columnName[i]);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(1 + i);
                row.createCell(0).setCellValue(list.get(i).getLogId());
                row.createCell(1).setCellValue(list.get(i).getUserName());
                row.createCell(2).setCellValue(list.get(i).getIpAddr());
                row.createCell(3).setCellValue(list.get(i).getLoginLocation());
                row.createCell(4).setCellValue(list.get(i).getBrowser());
                row.createCell(5).setCellValue(list.get(i).getOs());
                row.createCell(6).setCellValue(list.get(i).getStatus());
                row.createCell(7).setCellValue(list.get(i).getMsg());
                String format = sdf.format(list.get(i).getLoginTime());
                row.createCell(8).setCellValue(format);
            }
            workbook.write(out);
            workbook.close();
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
